<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>处方流转订单管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .filter-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .filter-section h3 {
            margin-bottom: 15px;
            color: #2c3e50;
        }

        .filter-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-item label {
            font-weight: bold;
            color: #555;
        }

        .filter-item input, .filter-item select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .filter-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }

        .filter-btn:hover {
            background: #2980b9;
        }

        .data-section {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .status-tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }

        .status-tab {
            padding: 15px 25px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 14px;
            color: #6c757d;
            transition: all 0.3s;
        }

        .status-tab.active {
            background: white;
            color: #3498db;
            border-bottom: 2px solid #3498db;
        }

        .status-tab:hover {
            background: #e9ecef;
        }

        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }

        th {
            background: #f8f9fa;
            font-weight: bold;
            color: #495057;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-invalid {
            background: #f8d7da;
            color: #721c24;
        }

        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
            transition: background 0.3s;
        }

        .view-btn {
            background: #17a2b8;
            color: white;
        }

        .view-btn:hover {
            background: #138496;
        }

        .delete-btn {
            background: #dc3545;
            color: white;
        }

        .delete-btn:hover {
            background: #c82333;
        }

        .pagination-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            background: white;
            border-top: 1px solid #dee2e6;
        }

        .batch-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .select-all {
            margin-right: 10px;
        }

        .batch-delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .batch-delete-btn:hover {
            background: #c82333;
        }

        .pagination-info {
            color: #6c757d;
            font-size: 14px;
        }

        .pagination-controls {
            display: flex;
            gap: 5px;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #dee2e6;
            background: white;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .page-btn:hover {
            background: #e9ecef;
        }

        .page-btn.active {
            background: #3498db;
            color: white;
            border-color: #3498db;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .error {
            text-align: center;
            padding: 40px;
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>处方流转订单管理</h1>
        </div>

        <div class="filter-section">
            <h3>筛选</h3>
            <div class="filter-row">
                <div class="filter-item">
                    <label>患者姓名或手机号</label>
                    <input type="text" id="patientSearch" placeholder="输入患者姓名或手机号">
                </div>
                <div class="filter-item">
                    <label>开始时间</label>
                    <input type="date" id="startTime">
                </div>
                <div class="filter-item">
                    <label>结束时间</label>
                    <input type="date" id="endTime">
                </div>
                <div class="filter-item">
                    <label>&nbsp;</label>
                    <button class="filter-btn" onclick="filterData()">筛选</button>
                </div>
            </div>
        </div>

        <div class="data-section">
            <div class="status-tabs">
                <button class="status-tab active" onclick="switchStatus(null)">全部</button>
                <button class="status-tab" onclick="switchStatus(0)">待支付</button>
                <button class="status-tab" onclick="switchStatus(1)">已完成</button>
                <button class="status-tab" onclick="switchStatus(2)">已失效</button>
            </div>

            <div class="table-container">
                <table id="orderTable">
                    <thead>
                        <tr>
                            <th><input type="checkbox" class="select-all" onclick="toggleSelectAll()"></th>
                            <th>订单编号</th>
                            <th>处方编号</th>
                            <th>患者</th>
                            <th>科室</th>
                            <th>医生</th>
                            <th>费用</th>
                            <th>订单状态</th>
                            <th>处方单状态</th>
                            <th>购药方式</th>
                            <th>发药状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="orderTableBody">
                        <tr>
                            <td colspan="12" class="loading">加载中...</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="pagination-section">
                <div class="batch-actions">
                    <input type="checkbox" class="select-all" onclick="toggleSelectAll()">
                    <button class="batch-delete-btn" onclick="batchDelete()">批量删除</button>
                </div>
                <div class="pagination-info" id="paginationInfo">
                    共0页/0条数据
                </div>
                <div class="pagination-controls" id="paginationControls">
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let pageSize = 10;
        let currentStatus = null;
        let totalPages = 0;
        let totalCount = 0;
        let selectedOrders = new Set();

        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadData();
        });

        // 加载数据
        async function loadData() {
            try {
                const params = new URLSearchParams({
                    pageIndex: currentPage,
                    pageSize: pageSize
                });

                if (currentStatus !== null) {
                    params.append('status', currentStatus);
                }

                const patientSearch = document.getElementById('patientSearch').value;
                if (patientSearch) {
                    params.append('patientNameOrPhone', patientSearch);
                }

                const startTime = document.getElementById('startTime').value;
                if (startTime) {
                    params.append('startTime', startTime);
                }

                const endTime = document.getElementById('endTime').value;
                if (endTime) {
                    params.append('endTime', endTime);
                }

                const response = await fetch(`/api/PrescriptionOrder/list?${params}`);
                const result = await response.json();

                if (result.success) {
                    displayData(result.data);
                } else {
                    showError(result.message || '获取数据失败');
                }
            } catch (error) {
                console.error('Error:', error);
                showError('网络错误，请稍后重试');
            }
        }

        // 显示数据
        function displayData(data) {
            const tbody = document.getElementById('orderTableBody');
            totalPages = data.totalPages;
            totalCount = data.totalCount;
            currentPage = data.currentPage;

            if (data.items.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" class="loading">暂无数据</td></tr>';
                updatePagination();
                return;
            }

            tbody.innerHTML = data.items.map(item => `
                <tr>
                    <td><input type="checkbox" class="order-checkbox" value="${item.id}" onchange="toggleOrderSelection(${item.id})"></td>
                    <td>${item.orderNo || '-'}</td>
                    <td>${item.prescriptionNo || '-'}</td>
                    <td>${item.patientName || '-'}</td>
                    <td>${item.departmentName || '-'}</td>
                    <td>${item.doctorName || '-'}</td>
                    <td>￥${item.paymentAmount || 0}</td>
                    <td><span class="status-badge status-${getStatusClass(item.status)}">${item.statusText || '-'}</span></td>
                    <td>${item.prescriptionStatusText || '-'}</td>
                    <td>${item.purchaseMethod || '-'}</td>
                    <td>${item.dispensingStatus || '-'}</td>
                    <td>
                        <button class="action-btn view-btn" onclick="viewOrder(${item.id})">查看</button>
                        ${item.status === 2 ? `<button class="action-btn delete-btn" onclick="deleteOrder(${item.id})">删除</button>` : ''}
                    </td>
                </tr>
            `).join('');

            updatePagination();
        }

        // 获取状态样式类
        function getStatusClass(status) {
            switch (status) {
                case 0: return 'pending';
                case 1: return 'completed';
                case 2: return 'invalid';
                default: return 'pending';
            }
        }

        // 更新分页信息
        function updatePagination() {
            document.getElementById('paginationInfo').textContent = `共${totalPages}页/${totalCount}条数据`;
            
            const controls = document.getElementById('paginationControls');
            let html = '';

            // 上一页
            if (currentPage > 1) {
                html += `<button class="page-btn" onclick="goToPage(${currentPage - 1})">&lt;</button>`;
            }

            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
            }

            // 下一页
            if (currentPage < totalPages) {
                html += `<button class="page-btn" onclick="goToPage(${currentPage + 1})">&gt;</button>`;
            }

            controls.innerHTML = html;
        }

        // 切换状态
        function switchStatus(status) {
            currentStatus = status;
            currentPage = 1;
            
            // 更新标签样式
            document.querySelectorAll('.status-tab').forEach(tab => tab.classList.remove('active'));
            event.target.classList.add('active');
            
            loadData();
        }

        // 筛选数据
        function filterData() {
            currentPage = 1;
            loadData();
        }

        // 跳转到指定页
        function goToPage(page) {
            currentPage = page;
            loadData();
        }

        // 全选/取消全选
        function toggleSelectAll() {
            const checkboxes = document.querySelectorAll('.order-checkbox');
            const selectAllCheckbox = document.querySelector('.select-all');
            
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
                if (selectAllCheckbox.checked) {
                    selectedOrders.add(parseInt(checkbox.value));
                } else {
                    selectedOrders.delete(parseInt(checkbox.value));
                }
            });
        }

        // 切换订单选择
        function toggleOrderSelection(orderId) {
            if (selectedOrders.has(orderId)) {
                selectedOrders.delete(orderId);
            } else {
                selectedOrders.add(orderId);
            }
        }

        // 查看订单详情
        function viewOrder(orderId) {
            alert(`查看订单详情：${orderId}`);
            // 这里可以跳转到详情页面或打开模态框
        }

        // 删除订单
        async function deleteOrder(orderId) {
            if (!confirm('确定要删除这个订单吗？')) {
                return;
            }

            try {
                const response = await fetch(`/api/PrescriptionOrder/${orderId}`, {
                    method: 'DELETE'
                });
                const result = await response.json();

                if (result.success) {
                    alert('删除成功');
                    loadData();
                } else {
                    alert(result.message || '删除失败');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('删除失败，请稍后重试');
            }
        }

        // 批量删除
        async function batchDelete() {
            if (selectedOrders.size === 0) {
                alert('请选择要删除的订单');
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedOrders.size} 个订单吗？`)) {
                return;
            }

            try {
                const response = await fetch('/api/PrescriptionOrder/batch', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(Array.from(selectedOrders))
                });
                const result = await response.json();

                if (result.success) {
                    alert('批量删除成功');
                    selectedOrders.clear();
                    loadData();
                } else {
                    alert(result.message || '批量删除失败');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('批量删除失败，请稍后重试');
            }
        }

        // 显示错误信息
        function showError(message) {
            const tbody = document.getElementById('orderTableBody');
            tbody.innerHTML = `<tr><td colspan="12" class="error">${message}</td></tr>`;
        }
    </script>
</body>
</html> 